import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadInstance, UploadProps, UploadUserFile } from 'element-plus'
import requirementApi from '@/api/purchase/requirement-api'
import projectApi from '@/api/inwarehouse/project-api'
import goodsApi from '@/api/inwarehouse/goods-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import * as _ from 'lodash';
import requestApi from '@/api/purchase/request-api'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const statusOptions = [
      { value: '0', label: '新建' },
      { value: '99', label: '已完成' },
      { value: '100', label: '已同步' }
    ]

    const orderCtx = reactive(new TableContext(getCurrentInstance(), {
      title: '物料清单',
      api: requirementApi,
      columns: [
        // { prop: 'serialId', label: '单号', valueType: 'input' },
        { prop: 'projectName', label: '项目', valueType: 'slot' },
        // { prop: 'locationCode', label: '产品序列号', valueType: 'input' },
        { prop: 'blueprintName', label: '图纸名称', valueType: 'slot' },
        // { prop: 'lastIncoming', label: '来料日期', },
        // { prop: 'status', label: '状态', slot: true, valueType: 'select', options: statusOptions },
        { prop: 'operation', label: '操作', slot: true }
      ],

      other: {
        getStatus(val) {
          if (!val) {
            return '-'
          }
          return statusOptions.find(item => {
            return item.value === val
          }).label
        },
        handleSkuChange(val: string, scope) {
          const obj = data.goodsOptions.find(item => {
            return item.barCode === val
          })
          const index = orderGoodsCtx.data.findIndex(item => {
            return item.barCode === scope.row.barCode
          })
          orderGoodsCtx.data.splice(index, 1, obj);
        },
        // handelProjectChange(val: string) {
        //   const obj = data.projectOptions.find(item => {
        //     return item.name === val
        //   })
        //   if (!obj) {
        //     return
        //   }
        //   orderCtx.editData.projectId = obj['id']
        //   orderCtx.editData.projectOriginalNo = obj['originalNo']
        // },
        showEdit(row) {
          data.goodsOptions = [];
          orderGoodsCtx.data = [];
          orderCtx.showEdit(row).then(d => {
            orderGoodsCtx.data = orderCtx.editData?.orderGoodsList;
          });
        },
      }
    }));


    const orderGoodsCtx = reactive(new TableContext(getCurrentInstance(), {
      pageSize: 0,
      selection: false,
      columns: [
        { prop: 'skuName', label: '物料名称', slot: true, width: 300 },
        { prop: 'barCode', label: '物料编码' },
        { prop: 'specification', label: '规格型号' },
        { prop: 'number', label: '数量', slot: true },
        // { prop: 'number1', label: '到货', slot: true },
        { prop: 'unit', label: '单位' },
      ],

    }))


    const importCtx = reactive(new TableContext(getCurrentInstance(), {
      title: '物料清单',
      pageSize: 0,
      selection: false,
      expand: true,
      defaultExpandAll: true,
      rowClassName: "tableRowClassName",
      columns: [
        { prop: 'num', label: '序号' },
        // { prop: 'skuCode', label: '标号' },
        { prop: 'skuName', label: '物料名称' },
        { prop: 'specification', label: '规格型号' },
        { prop: 'number', label: '需求数量' },
        { prop: 'remark', label: '备注' },
        // { prop: 'goodsList', label: '匹配的物料', slot: true },
      ],
      rules: {
        projectName: [{ required: true, message: '请选择项目', trigger: 'change' }],
        // code: [{ required: true, message: '请输入柜号', trigger: 'blur' }],
        blueprintName: [{ required: true, message: '请输入图纸名称', trigger: 'blur' }],
      },

      other: {
        // 导入
        import: async (options) => {
          importCtx.editData = {}
          importCtx.importLoading = true
          importCtx.data = []
          const res = await requirementApi.upload({ file: options.file })
          importCtx.importLoading = false
          if (res.data && res.data.length > 0) {
            importCtx.data = res.data
            importCtx.editVisible = true

            //姚宝杰非要需求数量自己带出来
            res.data?.map(o => {
              o.searchSkuName = o.skuName;
              o.searchSpecification = o.specification;
              o.goodsList?.map(x => {
                x.needNumber = o.number;

              });
            })
          }
          importCtx.importFiles = [];
        },
        importMultiple: async (options) => {
          importCtx.editData = {}
          importCtx.importLoading = true
          importCtx.data = []
          const res = await requirementApi.uploadMultiple({ file: options.file })
          importCtx.importLoading = false
          if (res.data && res.data.length > 0) {
            importCtx.data = res.data
            importCtx.editVisible = true

            //姚宝杰非要需求数量自己带出来
            res.data?.map(o => {
              o.searchSkuName = o.skuName;
              o.searchSpecification = o.specification;
              o.goodsList?.map(x => {
                x.needNumber = o.number;

              });
            })
          }
          importCtx.importFiles = [];
        },
        handelProjectChange(val: string) {
          const obj = data.projectOptions.find(item => {
            return item.name === val
          })
          if (!obj) {
            return
          }
          importCtx.editData.projectId = obj.id
          importCtx.editData.projectName = obj.name
          importCtx.editData.projectOriginalNo = obj.originalNo
        },
        submit: async () => {
          await importCtx.formRef.validate(async validated => {
            if (!validated) {
              document.getElementById("import-top").scrollIntoView();
              return;
            }
            if (!importCtx.editData.projectOriginalNo) {
              ElMessage.warning('项目没有合同号');
              return;
            }
            // var code = importCtx.editData.code.replaceAll("，", ",").split(",").map(o => o.trim()).filter(o => o).join(",");
            // if (!code) {
            //   ElMessage.warning('请输入柜号');
            //   return;
            // }
            const needMore = importCtx.data.filter(o => o.number != _.sumBy(o.goodsList, (x: any) => x.needNumber ? parseFloat(x.needNumber) : 0));
            if (needMore?.length) {
              ElMessage.warning('请检查需求数量 ' + needMore.map(o => o.skuName).join(' , '));
              return;
            }
            // code = code.split(',').map(o => `${importCtx.editData.projectOriginalNo}-${o}`).join(",");

            ElMessageBox.confirm(`确认当前已选数据生成物料清单及请购单？`, '温馨提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true
            })
              .then(async () => {
                // const arr = importCtx.data.map(item => {
                //   item.goodsId = item.id;
                //   item.id = null;
                //   return item;
                // });
                const requirementGoodsList = _.flatMap(importCtx.data, "goodsList").filter(o => o.needNumber).map(x => {
                  const o = _.clone(x);
                  o.goodsId = o.id;
                  o.id = null;
                  o.number = o.needNumber;
                  o.number1 = 0;
                  return o;
                });

                const requirementParams = {
                  ...importCtx.editData,
                  // locationCode: code,
                  orderGoodsList: requirementGoodsList
                };
                requirementApi.batchSave(requirementParams).then(res => {
                  if (res.success) {
                    ElMessage.success('新增成功')
                    orderCtx.loadData()
                    importCtx.editVisible = false
                  };
                });


                const requestGoodsList = _.flatMap(importCtx.data, "goodsList").filter(o => o.requestNumber).map(x => {
                  const o = _.clone(x);
                  o.goodsId = o.id;
                  o.id = null;
                  o.number = o.requestNumber;
                  o.number1 = 0;
                  return o;
                });
                if (requestGoodsList?.length) {
                  const requestParams = {
                    ...importCtx.editData,
                    status: '0',
                    date: new Date(),
                    orderGoodsList: requestGoodsList
                  }
                  requestApi.save(requestParams)
                }

                // if (res.code === 200) {
                //   ElMessage.success('新增成功')
                //   ctx.loadData()
                //   data.requirementDialog = false
                // }

              })
              .catch()
          });

        },
        searchSku: async (row) => {
          const res = await goodsApi.list({ otherFilter: { skuName: row.searchSkuName, specification: row.searchSpecification } });
          if (res.success) {
            row.goodsList = res.data.records;
          }
        },

      }
    }))


    const getProjectList = async () => {
      const params = { filter: { disabled: false } }
      const res = await projectApi.list(params)
      data.projectOptions = res.data.records
    }

    const getGoodsList = async (val: string) => {
      data.loading = true;
      const params = { otherFilter: { skuName: val } }
      const res = await goodsApi.list(params)
      data.loading = false;
      data.goodsOptions = res.data.records;
    }



    const data = reactive({
      getGoodsList,
      orderCtx,
      orderGoodsCtx,
      importCtx,
      projectOptions: [],
      loading: false,
      goodsOptions: []
    })

    // init
    onMounted(() => {
      getProjectList()
      orderCtx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
